import { defineConfig } from '@rspack/cli';
import { rspack } from '@rspack/core';
import * as RefreshPlugin from '@rspack/plugin-react-refresh';
import { TsCheckerRspackPlugin } from 'ts-checker-rspack-plugin';
const isDev = process.env.NODE_ENV === 'development';

// Target browsers, see: https://github.com/browserslist/browserslist
const targets = ['chrome >= 87', 'edge >= 88', 'firefox >= 78', 'safari >= 14'];

export default defineConfig({
  context: __dirname,
  entry: {
    main: './src/main.tsx'
  },
  devServer: {
    port: 4200
  },
  output: {
    //开发模式下，不需要 contenthash，因为 contenthash 会导致热更新失效
    filename: '[name].js',
    cssFilename: '[name].css'
  },
  resolve: {
    extensions: ['...', '.ts', '.tsx', '.jsx']
  },
  module: {
    parser: {
      'css/auto': {
        namedExports: false
      }
    },
    rules: [
      {
        test: /\.svg$/,
        type: 'asset'
      },
      {
        test: /\.(jsx?|tsx?)$/,
        use: [
          {
            loader: 'builtin:swc-loader',
            options: {
              jsc: {
                parser: {
                  syntax: 'typescript',
                  tsx: true
                },
                transform: {
                  react: {
                    runtime: 'automatic',
                    development: isDev,
                    refresh: isDev
                  }
                }
              },
              env: { targets }
            }
          },
        ],
        exclude: /node_modules/
      },
      {
        test: /\.(sass|scss)$/,
        type: 'css/auto',
        use: [
          {
            loader: 'sass-loader',
            options: {
              // 同时使用 `modern-compiler` 和 `sass-embedded` 可以显著提升构建性能
              // 需要 `sass-loader >= 14.2.1`
              api: 'modern-compiler'
              //implementation: require.resolve('sass-embedded'),
            }
          }
        ],
        exclude: /node_modules/
        // 如果你需要将 '*.module.(sass|scss)' 视为 CSS Module 那么将 'type' 设置为 'css/auto' 否则设置为 'css'
      }
    ]
  },
  plugins: [
    new rspack.HtmlRspackPlugin({
      template: './index.html'
    }),
    new TsCheckerRspackPlugin({
      devServer: isDev,
    }),
    isDev ? new RefreshPlugin() : null
  ].filter(Boolean),
  optimization: {
    minimizer: [
      new rspack.SwcJsMinimizerRspackPlugin(),
      new rspack.LightningCssMinimizerRspackPlugin({
        minimizerOptions: { targets }
      })
    ]
  },
  experiments: {
    css: true
  }
});
